<template>
  <van-dialog v-model="visible"  class="chat-record" title="Voice Record" :before-close="onClose" :show-confirm-button="false"  :show-cancel-button="false" close-on-click-overlay>
    <div v-show="mode == 'RECORD'" class="record-content">
      <div class="tip">{{ stateTip }}</div>
      <div>Time: {{ state == 'STOP' ? 0 : parseInt(rc.duration) }}s</div>
    </div>
    <audio v-show="mode == 'PLAY'" :src="url" controls ref="audio" @ended="onStopAudio()"></audio>
    <el-divider content-position="center"></el-divider>
    <el-row class="btn-group">
      <el-button class="custom-btn" round type="primary" v-show="state == 'STOP'" @click="onStartRecord()">Start Recording</el-button>
      <el-button class="custom-btn" round type="warning" v-show="state == 'RUNNING'" @click="onPauseRecord()">Pause Recording</el-button>
      <el-button class="custom-btn" round type="primary" v-show="state == 'PAUSE'" @click="onResumeRecord()">Rerecord</el-button>
      <el-button class="custom-btn" round type="danger" v-show="state == 'RUNNING' || state == 'PAUSE'" @click="onCompleteRecord()">
        Finish Recording</el-button>
      <el-button class="custom-btn" round v-show="state == 'COMPLETE' && mode != 'PLAY'" type="success"  @click="onPlayAudio()">Play Recording</el-button>
      <el-button class="custom-btn" round type="warning" v-show="state == 'COMPLETE' && mode == 'PLAY'" @click="onStopAudio()">Stop Playing
      </el-button>
      <el-button class="custom-btn" round v-show="state == 'COMPLETE'" type="primary" @click="onRestartRecord()">Re-recording</el-button>
      <el-button class="custom-btn" round v-show="state == 'COMPLETE'" type="primary"  @click="onSendRecord()">Send now</el-button>
    </el-row>
  </van-dialog>
</template>

<script>
import Recorder from 'js-audio-recorder';

export default {
	name: 'chatRecord',
	props: {
		visible: {
			type: Boolean
		}
	},
	data() {
		return {
			rc: new Recorder(),
			audio: new Audio(),
			state: 'STOP', // STOP、RUNNING、PAUSE、COMPLETE
			stateTip: "Not started",
			mode: 'RECORD', // RECORD 、PLAY
			duration: 0,
			url: ""
		}
	},
	methods: {
		onClose() {
			this.rc.destroy();
			this.rc = new Recorder();
			this.audio.pause();
			this.mode = 'RECORD';
			this.state = 'STOP';
			this.stateTip = 'Not started';
			this.$emit("close");
		},
		onStartRecord() {
			this.rc.start().then((stream) => {
				this.state = 'RUNNING';
				this.stateTip = "Recording...";
			}).catch(error => {
				this.$message.error(error);
			});
		},
		onPauseRecord() {
			this.rc.pause();
			this.state = 'PAUSE';
			this.stateTip = "Recording paused";
		},
		onResumeRecord() {
			this.rc.resume();
			this.state = 'RUNNING';
			this.stateTip = "Recording...";
		},
		onCompleteRecord() {
			this.rc.pause();
			this.state = 'COMPLETE';
			this.stateTip = "Recording ended";
		},
		onPlayAudio() {
			let wav = this.rc.getWAVBlob();
			let url = URL.createObjectURL(wav);
			this.$refs.audio.src = url;
			this.$refs.audio.play();
			this.mode = 'PLAY';
		},
		onStopAudio() {
			this.$refs.audio.pause();
			this.mode = 'RECORD';
		},
		onRestartRecord() {
			this.rc.destroy();
			this.rc = new Recorder()
			this.rc.start();
			this.state = 'RUNNING';
			this.mode = 'RECORD';
			this.stateTip = "Recording...";
		},
    async onSendRecord() {
			let wav = this.rc.getWAVBlob();
			let name = new Date().getDate() + '.wav';
			var formData = new window.FormData()

      var cryptoInstance = this.$store.getters.cryptoInstance();
      var encryptFile = await cryptoInstance.cryptoUtil.encryptFileReal(cryptoInstance, wav);
      formData.append('file', encryptFile, name)


      this.$http({
				url: '/file/upload',
				data: formData,
				method: 'post',
				headers: {
					'Content-Type': 'multipart/form-data'
				}
			}).then((url) => {
				let data = {
					duration: parseInt(this.rc.duration),
					// url: url
				}
        data = {...data, ...url}
				this.$emit("send", data);
				this.onClose();
			})
		}
	}
}
</script>

<style lang="scss">
.chat-record {
  .record-content {
    text-align: center;
    margin: 20px 0;
  }
	.tip {
		font-size: 18px;
    margin-bottom: 10px;
	}

	.btn-group {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    gap: 10px;
		margin-bottom: 20px;
    text-align: center;

    .custom-btn {
      width: 80%;
    }
	}
}
</style>
